package com.komorebi.friends.controller;

import com.komorebi.friends.common.ErrorCode;
import com.komorebi.friends.exception.BusinessException;
import com.komorebi.friends.model.dto.groupMsg.GroupMsgRequest;
import com.komorebi.friends.model.entity.GroupMsgContent;
import com.komorebi.friends.model.entity.User;
import com.komorebi.friends.model.vo.MessageVO;
import com.komorebi.friends.service.GroupMsgContentService;
import com.komorebi.friends.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

@RestController
public class WebSocketController {

    @Autowired
    SimpMessagingTemplate simpMessagingTemplate;

    @Autowired
    GroupMsgContentService groupMsgContentService;

    @Autowired
    UserService userService;

    /**
     * 群聊消息的接受与转发
     * @param request
     * @param groupMsgRequest
     */
    @MessageMapping("/ws/groupChat")
    public void handleGroupMessage(HttpServletRequest request, GroupMsgRequest groupMsgRequest){
        //取出用户
        User loginUser = userService.getLoginUser(request);
        //目的队伍群聊
        Long teamId = groupMsgRequest.getTeamId();
        if(teamId == null || teamId < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请给存在的队伍发消息");
        }

        GroupMsgContent groupMsgContent = groupMsgRequest.getGroupMsgContent();

        //保存该条消息到数据库
        groupMsgContentService.insert(loginUser,groupMsgRequest);

        //群聊消息转发
        simpMessagingTemplate.convertAndSend("/topic/greetings" + teamId, groupMsgContent);
    }

    /**
     * 单聊
     * @param request
     * @param messageVo
     */
    @MessageMapping("/ws/chat")
    public void handleMessage(HttpServletRequest request, MessageVO messageVo){
        User loginUser = userService.getLoginUser(request);
        messageVo.setFrom(loginUser.getId());
        messageVo.setCreateTime(new Date());
        simpMessagingTemplate.convertAndSendToUser(messageVo.getTo().toString(),"/queue/chat",messageVo);
    }

}
